package cn.cool.infrastructure.dcc;

import cn.cool.types.annotation.DCCValue;
import cn.cool.types.common.Constants;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Service("dccService")
@Slf4j
//@Data
public class DCCService {
    @DCCValue("downgradeSwitch:0")
    private String downgradeSwitch;

    @DCCValue("cutRange:5")
    private String cutRange;

    @DCCValue("scBlackList:s02c02")
    private String scBlackList;

    @DCCValue("defaultLockOrderLimit:5")
    private String defaultLockOrderLimit;

    @DCCValue("hotParamFlowRules:{}")
    private String hotParamFlowRules;

    @DCCValue("cacheOpenSwitch:0")
    private String cacheOpenSwitch;


    private static final String DOWNGRADE = "1";

    @Resource
    private RedissonClient redissonClient;

    // 缓存已初始化的限流器
    private static final String RATE_LIMITER_PREFIX = "group_buy:goods:limiter:";
    private static final ConcurrentMap<String, RRateLimiter> LIMITER_CACHE = new ConcurrentHashMap<>();


    /**
     * 是否降级
     */
    public boolean isDowngradeSwitch() {
        return DOWNGRADE.equals(downgradeSwitch);
    }

    /**
     * 是否限流
     * @param goodsId
     * @return
     */
    public boolean isCutRange(String goodsId) {
        try {
            final String limiterKey = RATE_LIMITER_PREFIX + goodsId;
            int currentConfiguredRate = Integer.parseInt(cutRange);
            // 从缓存获取或者创建限流器
            RRateLimiter rateLimiter = LIMITER_CACHE.computeIfAbsent(limiterKey, key -> redissonClient.getRateLimiter(key));
            // 检查当前速度是否需要更新
            RateLimiterConfig config = rateLimiter.getConfig();
            if (config == null || config.getRate() != currentConfiguredRate) {
                rateLimiter.setRate(RateType.OVERALL, currentConfiguredRate, 1, RateIntervalUnit.SECONDS);
                log.info("更新限流器 {} 的速率为 {}", limiterKey, currentConfiguredRate);
            }
            return rateLimiter.tryAcquire(1);
        } catch (Exception e) {
            throw new RuntimeException("限流组件异常！", e);
        }
    }

    public boolean isSCBlackIntercept(String source, String channel) {
        List<String> list = Arrays.asList(scBlackList.split(Constants.SPLIT));
        return list.contains(source + channel);
    }

    public Integer getDefaultLockOrderLimit() {
        return Integer.parseInt(defaultLockOrderLimit);
    }

    public String getHotParamFlowRules() {
        return hotParamFlowRules;
    }

    /**
     * 缓存开启开关，0为开启，1为关闭
     */
    public boolean isCacheOpenSwitch() {
        return "0".equals(cacheOpenSwitch);
    }

    @PreDestroy
    public void destroy() {
        LIMITER_CACHE.clear();
    }
}
